#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

//int msgget(key_t key, int msgflg);
//key_t ftok(const char *pathname, int proj_id);



struct msgbuf {
	long mtype;       /* message type, must be > 0 */
	char mtext[128];    /* message data */
};



int main(){

	struct msgbuf msg;
	key_t key;
	int msqid;
	
	if((key = ftok(".",'m')) == -1){
		
		perror("ftok error");
		exit(1);
	}

	printf("Client key = %x\n",key);

	if((msqid = msgget(key,IPC_CREAT|0777)) == -1){
	
		perror("msgget error");
		exit(1);
	}

	printf("Client pid = %d\n",getpid());
	printf("msqid = %d\n",msqid);
	

//ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
	msgrcv(msqid,&msg,128,888,0);
	printf("Receive server msg\nmsg.mtype=%ld\nmsg.mtext=%s\n",msg.mtype,msg.mtext);

//int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
	msg.mtype = 999;
	sprintf(msg.mtext,"Hello,I'm client is %d\n",getpid());
	msgsnd(msqid,&msg,128,0);

	msgctl(msqid,IPC_RMID,NULL);

	return 0;
}
